package com.example.websocket.websocket;

import org.java_websocket.WebSocket;

import java.util.*;

public class WsPool {
    private static final Map<WebSocket, String> wsUserMap = new HashMap<WebSocket, String>();

    public static void addUser(String userName, WebSocket conn){
        wsUserMap.put(conn, userName);
    }

    public static boolean removeUser(WebSocket conn){
        if (wsUserMap.containsKey(conn)){
            wsUserMap.remove(conn);
            return true;
        }else {
            return false;
        }
    }

    public static void sendMsgToUser(WebSocket conn, String msg){
        if (null != wsUserMap.get(conn)){
            conn.send(msg);
        }
    }

    public static void sendMsgToAll(String msg){
        Set<WebSocket> keySets = wsUserMap.keySet();
        synchronized (keySets){
            for (WebSocket conn : keySets){
                String user = wsUserMap.get(conn);
                if (user != null){
                    conn.send(msg);
                }
            }
        }
    }

    public static WebSocket findWebSocket(String userName){
        Set<WebSocket> sockets = wsUserMap.keySet();
        Collection<String> value = wsUserMap.values();
        Object[] strings = value.toArray();
        for (int i = 0; i < strings.length; i ++) {
            if (strings[i].equals(userName)) {
                return (WebSocket) sockets.toArray()[i];
            }
        }
        return null;
    }

}
